package com.juicygames.undoer.player;

import android.view.MotionEvent;

import com.juicygames.framework.action.TouchAction;
import com.juicygames.framework.gamepart.GameHandler;
import com.juicygames.framework.gamepart.GamePart;
import com.juicygames.framework.property.BooleanProperty;
import com.juicygames.framework.property.IntegerProperty;
import com.juicygames.framework.property.space.CircleProperty;
import com.juicygames.framework.property.space.XVelocity;
import com.juicygames.framework.property.space.YVelocity;
import com.juicygames.framework.type.Point;
import com.juicygames.undoer.ball.OldPosition;
import com.juicygames.undoer.player.property.CanMakeShadow;
import com.juicygames.undoer.player.property.IsTouched;

public class TouchHandler extends GameHandler<TouchAction> {
	
	public TouchHandler(GamePart self) {
		super(self);
		setActionClassHandled(TouchAction.class);
	}
	
	public void handle(TouchAction touch) {
		super.handle(touch);
		
		MotionEvent event = touch.getEvent();
		IsTouched isTouched = self.getPart(IsTouched.class);
		
		if (event.getAction() == MotionEvent.ACTION_DOWN && doesCollide(new Point(event.getX(),event.getY()))) {
			handleTouchPress(touch);
		}
		else if (isTouched.get() && event.getAction() == MotionEvent.ACTION_UP) {
			handleTouchRelease(touch);
		}
		else if (isTouched.get()) {
			handleTouchDrag(touch);
		}
	}
	
	private boolean doesCollide(Point p) {
		CircleProperty circle = self.getPart(CircleProperty.class);
		return circle.get().doesCollide(p);
	}
	
	private void handleTouchPress(TouchAction touch) {
		BooleanProperty isTouched = self.getPart(IsTouched.class);
		isTouched.set(true);
		
		BooleanProperty canMakeShadow = self.getPart(CanMakeShadow.class);
		canMakeShadow.set(true);
		
		CircleProperty circle = self.getPart(CircleProperty.class);
		circle.get().radius = Player.BIG_RADIUS;
		circle.get().x = (int)touch.getEvent().getX();
		circle.get().y = (int)touch.getEvent().getY();
		
		IntegerProperty xVel = self.getPart(XVelocity.class);
		IntegerProperty yVel = self.getPart(YVelocity.class);
		
		xVel.set(0);
		yVel.set(0);
	}
	
	private void handleTouchDrag(TouchAction touch) {
		MotionEvent event = ((TouchAction)touch).getEvent();
		CircleProperty circle = self.getPart(CircleProperty.class);
		circle.get().set(event.getX(),event.getY());
	}
	
	private void handleTouchRelease(TouchAction touch) {
		MotionEvent event = ((TouchAction)touch).getEvent();
		
		BooleanProperty isTouched = (BooleanProperty)self.getPart(IsTouched.class);
		isTouched.set(false);
		
		CircleProperty circle = self.getPart(CircleProperty.class);
		circle.get().radius = Player.SMALL_RADIUS;
		
		IntegerProperty xVel = self.getPart(XVelocity.class);
		IntegerProperty yVel = self.getPart(YVelocity.class);
		OldPosition oldPosition = self.getPart(OldPosition.class);
		
		xVel.set(event.getX() - oldPosition.get().x);
		yVel.set(event.getY() - oldPosition.get().y);
	}

}
